use tauri_plugin_autostart::MacosLauncher;
use std::io::Write;
use tauri::{ Manager };
use window_vibrancy::{apply_blur, apply_vibrancy, apply_acrylic, apply_mica, NSVisualEffectMaterial};

#[tauri::command]
fn greet(name: &str) -> String {
    format!("Hello, {}! You've been greeted from Rust!", name)
}

// 帮助前端 将 文件保存到本地，不使用 tauri 的原因是其 fs 模块的
// 文件的访问权限控制无法实现此功能
#[tauri::command]
fn created_file(name: &str, content: &str) -> String {
    let mut file = std::fs::File::create(name).expect("create file error");
    file.write_all(content.as_bytes()).expect("write file error");
    format!("ok")
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    tauri::Builder::default()
        .setup(|app|
            {
                let splashscreen_window = app.get_window("splashscreen").unwrap();
                let main_window = app.get_window("main").unwrap();

                #[cfg(target_os = "macos")]
                apply_vibrancy(&main_window, NSVisualEffectMaterial::HudWindow, None, None)
                    .expect("Unsupported platform! 'apply_vibrancy' is only supported on macOS");

                #[cfg(target_os = "windows")]
                apply_blur(&main_window, Some((5, 5, 5, 0)))
                    .expect("Unsupported platform! 'apply_blur' is only supported on Windows");


                tauri::async_runtime::spawn(async move {
                    std::thread::sleep(std::time::Duration::from_secs(2));
                    splashscreen_window.close().unwrap();
                    main_window.show().unwrap();



//                     main_window.open_devtools()
                });

                Ok(())
            })
//         .on_window_event(|event| {
//             let handle = event.window().app_handle();
//             let label = event.window().label();
//             match event.event() {
//                 WindowEvent::Focused(focused) => {
//                     println!("WindowEvent::Focused ==> {:?} {:?}", focused, label);
//                     if *focused {
//                         #[cfg(target_os = "macos")]
//                         match menu::setup_menu(handle, &label) {
//                             Ok(()) => {}
//                             Err(err) => println!("Failed to setup menu, {:?}", err),
//                         }
//                     }
//                 }
//                 _ => {}
//             }
//         })
        .plugin(tauri_plugin_clipboard_manager::init())
        .plugin(tauri_plugin_window::init())
        .plugin(tauri_plugin_fs::init())
        .plugin(tauri_plugin_shell::init())
        .plugin(tauri_plugin_notification::init())
        .plugin(tauri_plugin_dialog::init())
        .plugin(tauri_plugin_autostart::init(MacosLauncher::LaunchAgent, Some(vec!["--flag1", "--flag2"])))
        .invoke_handler(tauri::generate_handler![greet, created_file ])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
